<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select v-model="query.originalServer" class="filter-item" placeholder="请选择源服务器类型" filterable clearable style="width:200px">
          <el-option v-for="item in dict.source_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="query.targetServer" class="filter-item" placeholder="请选择目标服务器类型" filterable clearable style="width:200px;">
          <el-option v-for="item in dict.source_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="query.convertType" class="filter-item" placeholder="请选择转换类型" filterable clearable style="width:200px;">
          <el-option v-for="item in dict.data_transfer_table_convert_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-model="query.originalValue" clearable size="small" placeholder="请输入原值" style="width: 200px;" class="filter-item" />
        <rrOperation :crud="crud" />
      </div>
      <crudOperation show="" :permission="permission">
        <template v-slot:beforeExport>
          <el-button
            class="filter-item"
            :loading="downloadLoading"
            :disabled="!crud.selections.length"
            type="primary"
            size="mini"
            @click="exportData"
          ><i class="el-icon-download" />
            导出
          </el-button>
          <el-upload
            ref="uploadExcel"
            style="display: inline-block"
            class="upload-demo"
            :loading="uploadLoading"
            action=""
            multiple
            :auto-upload="false"
            :on-change="handleUploadJobChange"
            :file-list="fileList"
            :show-file-list="false"
          >
            <div>
              <el-button
                size="mini"
                class="filter-item"
                type="primary"
                icon="el-icon-upload2"
              >
                导入
              </el-button>
            </div>
          </el-upload>
        </template>
      </crudOperation>
      <el-table
        ref="table"
        :data="crud.data"
        @select="handleSelection"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column v-if="columns.visible('originalServer')" prop="originalServer" label="源服务器" />
        <el-table-column v-if="columns.visible('targetServer')" prop="targetServer" label="目标服务器" />
        <el-table-column v-if="columns.visible('convertType')" prop="convertType" label="转换类型">
          <template slot-scope="scope">
            {{ formatterConvertType(scope.row.convertType) }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('replaceType')" prop="replaceType" label="替换类型">
          <template slot-scope="scope">
            {{ formatterReplaceType(scope.row.replaceType) }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('originalValue')" prop="originalValue" label="原值" min-width="150" />
        <el-table-column v-if="columns.visible('targetValue')" prop="targetValue" label="目标值" min-width="150" />
        <el-table-column v-if="columns.visible('coefficient')" prop="coefficient" label="系数">
          <template slot-scope="scope">
            <p> {{ scope.row.coefficient === 0 ? '' : scope.row.coefficient }} </p>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('detail')" prop="detail" label="备注" min-width="150" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="openDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="32" />
      <el-dialog
        v-if="crud.status.cu > 0"
        append-to-body
        :close-on-click-modal="false"
        :modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="800px"
      >
        <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="源服务器类型" prop="originalServer">
            <el-select v-model="form.originalServer" placeholder="请选择" filterable clearable style="width:190px">
              <el-option v-for="item in dict.source_type" :key="item.key" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="目标服务器类型" prop="targetServer">
            <el-select v-model="form.targetServer" placeholder="请选择" filterable clearable style="width:190px">
              <el-option v-for="item in dict.source_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="转换类型" prop="convertType">
            <el-select v-model="form.convertType" placeholder="请选择" filterable clearable style="width:190px" @change="dynamicReplaceType">
              <el-option v-for="item in dict.data_transfer_table_convert_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="替换类型" prop="replaceType">
            <el-select v-model="form.replaceType" filterable placeholder="请选择" clearable style="width:190px">
              <el-option v-for="item in replaceList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.replaceType!=='prefix' && form.replaceType!=='suffix'" label="原值" prop="originalValue">
            <el-input v-model="form.originalValue" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="目标值" prop="targetValue">
            <el-input v-model="form.targetValue" placeholder="请输入" />
          </el-form-item>
          <el-form-item v-if="form.convertType==='fieldType'" label="系数">
            <el-input-number v-model="form.coefficient" :precision="1" :min="-1" :max="10" :step="0.5" controls-position="right" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form.detail"
              placeholder="请输入"
              style="width: 260px"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog
        append-to-body
        :close-on-click-modal="false"
        :before-close="detailClose"
        :visible.sync="detailFlag"
        title="详情"
        width="800px"
      >
        <el-form ref="form" :inline="true" label-width="130px" disabled>
          <el-form-item label="源服务器类型" prop="originalServer">
            <el-select v-model="detailForm.originalServer" placeholder="请选择" clearable style="width:190px">
              <el-option v-for="item in dict.source_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="目标服务器类型" prop="targetServer">
            <el-select v-model="detailForm.targetServer" placeholder="请选择" clearable style="width:190px">
              <el-option v-for="item in dict.source_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="转换类型" prop="convertType">
            <el-select v-model="detailForm.convertType" placeholder="请选择" clearable style="width:190px">
              <el-option v-for="item in dict.data_transfer_table_convert_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="替换类型" prop="replaceType">
            <el-select v-model="detailForm.replaceType" placeholder="请选择" clearable style="width:190px">
              <el-option v-for="item in dict.data_transfer_table_replace_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="原值">
            <el-input v-model="detailForm.originalValue" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="目标值">
            <el-input v-model="detailForm.targetValue" placeholder="请输入" />
          </el-form-item>
          <el-form-item v-if="detailForm.convertType==='fieldType'" label="系数">
            <el-input-number v-model="detailForm.coefficient" :precision="1" :min="-1" :max="10" :step="0.5" controls-position="right" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="detailForm.detail"
              style="width: 260px"
              type="textarea"
              :rows="2"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="detailClose">取消</el-button>
          <el-button v-if="detailFlag===false" type="primary" @click="detailClose">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import convertConfigApi from '@/api/data/convert/convertConfig'
import dataSourceApi from '@/api/metadata/dataSource'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import { upload } from '@/api/data'
import { downloadFile } from '@/utils'
import request from '@utils/request'

const defaultCrud = CRUD({
  title: '转换配置',
  url: '/api/convertConfig',
  crudMethod: { ...convertConfigApi }
})

const defaultForm = {
  pkId: '',
  originalServer: '',
  targetServer: '',
  convertType: '',
  replaceType: '',
  originalValue: '',
  targetValue: '',
  coefficient: '',
  detail: ''
}
export default {
  components: { crudOperation, rrOperation, pagination },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['data_transfer_table_convert_type', 'data_transfer_table_replace_type', 'source_type'],
  data() {
    return {
      fileList: [],
      acceptFileType: '.xls,.xlsx',
      uploadLoading: false,
      downloadLoading: false,
      permission: {
        add: ['admin', 'scriptConvert:add'],
        edit: ['admin', 'scriptConvert:edit'],
        del: ['admin', 'scriptConvert:del']
      },
      rules: {
        originalValue: [
          { required: true, message: '请输入原值', trigger: 'blur' }
        ],
        targetValue: [
          { required: true, message: '请输入目标值', trigger: 'blur' }
        ],
        originalServer: [{ required: true, message: '请选择原服务器', trigger: 'change' }],
        targetServer: [{ required: true, message: '请选择目标服务器', trigger: 'change' }],
        convertType: [{ required: true, message: '请选择转换类型', trigger: 'change' }],
        replaceType: [{ required: true, message: '请选择替换类型', trigger: 'change' }]

      },
      detailFlag: false,
      detailForm: {},
      sourceList: [],
      convertList: [],
      replaceList: []
    }
  },
  created() {
    this.crud.resetQuery(false)
    this.initData()
  },
  methods: {
    [CRUD.HOOK.beforeToAdd](crud) {
      this.getDefaultSource()
    },
    handleUploadJobChange(file, fileList) {
      const fileName = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (fileName !== 'xlsx' && fileName !== 'xls') {
        this.crud.notify('文件类型应为excel文件!', CRUD.NOTIFICATION_TYPE.ERROR)
        this.fileList = []
        return false
      }
      this.fileList = fileList
      if (this.fileList.length > 0) {
        this.uploadLoading = true
        const formData = new FormData()
        this.fileList.forEach((element, i) => {
          formData.append('file', element.raw)
        })
        upload('api/convertConfig/importConvertConfig', formData).then(res => {
          this.uploadLoading = false
          if (res.status) {
            this.crud.notify('导入成功!', CRUD.NOTIFICATION_TYPE.SUCCESS)
            this.crud.refresh()
          } else {
            this.crud.notify('导入失败!', CRUD.NOTIFICATION_TYPE.ERROR)
          }
        })
      } else {
        this.$notify.error({
          title: '错误',
          message: '请选择导入的文件!'
        })
      }
    },
    exportData() {
      const pkIds = this.crud.selections.map(item => {
        return item.pkId
      })
      this.downloadLoading = true
      request({
        url: `api/convertConfig/exportConvertConfig?pkIds=${pkIds}`,
        method: 'get',
        responseType: 'blob'
      }).then(result => {
        downloadFile(result, '转换配置信息', 'xlsx')
        this.downloadLoading = false
      }).catch(() => {
        this.downloadLoading = false
      })
    },
    initData() {
      this.getDataSource()
    },
    getDataSource() {
      const param = {}
      dataSourceApi.findListByPage(param).then(data => {
        this.sourceList = data.content
      })
    },
    getDefaultSource() {
      dataSourceApi.findDefaultSource().then(data => {
        const sourceDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'source')
        const targetDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'target')
        this.form.originalServer = sourceDefault === undefined ? '' : sourceDefault.sourceType
        this.form.targetServer = targetDefault === undefined ? '' : targetDefault.sourceType
      })
    },
    handleSelection(ids) {
      this.crud.selections = ids
    },
    detailClose() {
      this.detailFlag = false
    },
    formatterConvertType(val) {
      return this.dict.label.data_transfer_table_convert_type[val]
    },
    formatterReplaceType(val) {
      return this.dict.label.data_transfer_table_replace_type[val]
    },
    openDetail(row) {
      this.detailForm = row
      this.detailFlag = true
    },
    // 根据转换类型动态获取替换类型
    dynamicReplaceType() {
      if (this.form.convertType === 'fieldType') {
        this.replaceList = this.dict.data_transfer_table_replace_type.filter(item => item.value !== 'prefix' && item.value !== 'suffix')
      } else {
        this.replaceList = this.dict.data_transfer_table_replace_type
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

</style>
